﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Agile.Engine.Xml
{
    
    public class XmlResource : Dictionary<string, object>
    {
        public void LoadConfig(string config)
        {
            var stream = Agile.Engine.Utils.IOUtils.InputStream(config);
            PaserResource(stream);
            stream.Close();
        }

        protected virtual void PaserResource(System.IO.Stream stream)
        {
            System.Xml.Linq.XElement root = System.Xml.Linq.XElement.Load(stream);
            foreach (var el in root.Elements("data").AsParallel())
            {
                this[el.Attribute("key").Value] = el.Value;
            }
        }

        /// <summary>
        /// 合并资源
        /// </summary>
        /// <param name="key"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public string Merge(string key, System.Collections.Hashtable model)
        {
            return Agile.Engine.Utils.VelocityUtils.MergeString(this[key].ToString(), model);
        }

        /// <summary>
        /// 格式化资源
        /// </summary>
        /// <param name="key"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public string Format(string key, params object[] args)
        {
            return string.Format(this[key].ToString(), args);
        }

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetString(string key)
        {
            return this[key].ToString();
        }

        public string ConfigUri
        {
            set { LoadConfig(value); }
        }
    }
}
